#coding:utf-8
import streamlit as st
import pandas as pd
import numpy as np

import io_util
from fin_api import *
import matplotlib.pyplot as plt
from matplotlib.font_manager import _rebuild

_rebuild() #reload一下
plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False #用来正常显示负号


plt.rcParams['font.family'] = 'Microsoft YaHei'
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei'] #更新字体格式
plt.rcParams['font.size'] = 9

st.set_option('deprecation.showPyplotGlobalUse', False)
# arr = np.random.normal(1, 1, size=100)
# plt.hist(arr, bins=20)
# st.pyplot()

def draw_col_by_idx(ys,col,indexs,title):
    chart_data = pd.DataFrame(ys, columns=[col], index=indexs)
    chart_data.plot()
    plt.title(title)
    st.pyplot()

def draw_today_line(code):
    resp = send_req(code)
    dta = (get_today_price(resp, code))
    st.title(code)
    chart_data = pd.DataFrame([[float(u[1])] for u in dta], columns=['price'], index=[u[0] for u in dta])
    chart_data.plot()
    plt.title(code + " price")
    st.pyplot()
# st.title('today')
# chart_data = pd.DataFrame(
#  np.random.randn(20, 3),
#   columns=['a', 'b', 'c'],index=["0"+str(n+1) if n+1 < 10 else str(n+1)  for n in range(20)])
#
@st.cache
def today_fund_rank(page):
    d = fund_order('hh', 'z', None, page, 10)
    return d

#st.text(funds)
@st.cache
def api_get_position(code):
    url = f'https://api.doctorxiong.club/v1/fund/position?code={code}'
    res = requests.get(url)
    return res.json()

def dic2df(dic_list):
    ks = dic_list[0].keys()
    ks = [k for k in ks]
    data = [[d[c] for  c in ks] for d in dic_list]
    return pd.DataFrame(data,columns=ks)

st.title("基金排行")
page =1
option_fund = False
key = 1
page = st.selectbox('翻页',["1","2","3","4","5","X"],key=str(key))
funds = []
if page!= 'X':
    key+=1
    funds = today_fund_rank(int(page))
    fundcode2name = { f['code']:f['name'] for f in funds}
    fund_name2code = { f['name']:f['code'] for f in funds}

    #st.write(funds)
    #st.write("<a>hello</a>")
    st.write(dic2df(funds))
    # option_funds = st.multiselect("选择基金",[u['name'] for u in funds ])
    # st.select_slider("slider",[u['name'] for u in funds ])
    key_j = 0
option_fund = st.selectbox("选择排行基金",[u['name'] for u in funds ])



#if len(option_funds)>0:
#    for option_fund in option_funds:
if option_fund:
    open_pos = st.button("查看持仓")
    code = fund_name2code.get(option_fund)
    if open_pos:

        if code:
            res = api_get_position(code)
            st.text("持仓是:")
            # st.write(res)
            df = pd.DataFrame(res['data']['stockList'], columns="股票代码,名称,占比,持有股数(万股),持有金额(万元)".split(','))
            st.dataframe(df, width=600)
    option_fund = st.selectbox("查看走势/(%)", ['绝对值',"涨幅"])
    #open_pic =  st.button("查看走势")
    if option_fund == '绝对值':
        if code:
            res = fund_code(code, '2021-07-01')
            date,prices = get_date_price(res)
            date = [d[5:] for d in date]
            draw_col_by_idx(prices,'price',date,'price over July')
    #open_pic2 =  st.button("查看走势 (%)")
    if option_fund == '涨幅':
        if code:
            res = fund_code(code, '2021-07-01')
            date,prices = get_date_price(res)
            a = prices[0]
            prices = [p / a for p in prices]
            date = [d[5:] for d in date]
            draw_col_by_idx(prices,'percent',date,'price over July')
st.title('自选基金')
fund_key_word = st.text_input('搜索基金')
full_fund_list = io_util.load_json('fund_list.json')
sub_list = [d for d in full_fund_list if fund_key_word in d['code'] or fund_key_word in d['name']]

option_fund2 = st.selectbox("选择基金",["{}|{}".format(d['code'],d['name']) for d in sub_list ])
st.text('你选择了'+option_fund2)

if option_fund2!='':
    open_pos = st.button("查看自选基金持仓")
    code= option_fund2.split('|')[0]
    #code = fund_name2code.get(option_fund2)
    if open_pos:

        if code:
            res = api_get_position(code)
            st.text("持仓是:")
            # st.write(res)
            df = pd.DataFrame(res['data']['stockList'], columns="股票代码,名称,占比,持有股数(万股),持有金额(万元)".split(','))
            st.dataframe(df, width=600)
    option = st.selectbox("查看自选基金走势/(%)", ['绝对值',"涨幅"])
    #open_pic =  st.button("查看走势")
    if option == '绝对值':
        if code:
            res = fund_code(code, '2021-07-01')
            date,prices = get_date_price(res)
            date = [d[5:] for d in date]
            draw_col_by_idx(prices,'price',date,'price over July')

    if option == '涨幅':
        if code:
            res = fund_code(code, '2021-07-01')
            date,prices = get_date_price(res)
            a = prices[0]
            prices = [p / a for p in prices]
            date = [d[5:] for d in date]
            draw_col_by_idx(prices,'percent',date,'price over July')


# st.line_chart(chart_data)
code = '000016'

code2name = io_util.load_json('stock_code2name.json')
#print(code2name)
name2code = {v:k for k,v in code2name.items()}
st.title("股票")
name = st.text_input("查询股票?")
if isinstance(name,str) :

    if len(name)>0:
        if name != '':
            print('in',name)
            buts = ''
            if code2name is None :
                st.text('name')
            else:
                st.text(name)
                stocks = [(code,stock ) for code,stock in code2name.items() if isinstance(stock,str) and isinstance(code,str)]
                stocks = [(code,stock )  for code,stock in stocks if name in stock or name in code]
                names = [stock for code,stock in stocks]
                # names = [v for v in code2name.values()]
                # names = [v for v in names if isinstance(v,str)]
                # names = [v for v in names if name in v]

                option_fund2 = st.selectbox("选择股票", ["{}|{}".format(name2code.get(d), d) for d in names])
                n = option_fund2
                code = option_fund2.split('|')[0]
                print('code in dict',n in name2code)
                print('code ',code)
                if isinstance(code,str):

                    if len(code)>0:
                        draw_today_line(code)





code = st.text_input("股票代码")
if code !='':
    draw_today_line(code)

